import React, { useState, useEffect } from 'react';
import { Layout, Menu, Avatar, Button, Space } from 'antd';
import {
  HomeOutlined,
  DatabaseOutlined,
  UploadOutlined,
  TeamOutlined,
  UserOutlined,
  LogoutOutlined,
  GlobalOutlined,
  ToolOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { auth } from '../services';
import { getUser } from '../utils/localStorage';

const { Header, Content, Footer, Sider } = Layout;

const CommonLayout = ({ children, setIsLoggedIn }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [user, setUser] = useState(null);

  // 根据当前路径设置选中的菜单项
  const getSelectedKey = () => {
    const path = location.pathname;
    if (path.includes('/home')) return '1';
    if (path.includes('/resources') || path.includes('/torrents') || path.includes('/categories')) return '2';
    if (path.includes('/upload')) return '3';
    if (path.includes('/topics')) return '4';
    if (path.includes('/broadcasts')) return '5';
    if (path.includes('/user-panel') || path.includes('/profile')) return '6';
    if (path.includes('/admin/tools')) return '7';
    return '1'; // 默认选中首页
  };

  const [selectedMenuKey, setSelectedMenuKey] = useState(getSelectedKey());

  useEffect(() => {
    // 获取当前用户信息
    const currentUser = getUser();
    setUser(currentUser);

    // 更新选中的菜单项
    setSelectedMenuKey(getSelectedKey());
  }, [location.pathname]);

  const handleMenuClick = (e) => {
    setSelectedMenuKey(e.key);

    switch (e.key) {
      case '1':
        navigate('/home');
        break;
      case '2':
        navigate('/resources');
        break;
      case '3':
        navigate('/upload');
        break;
      case '4':
        navigate('/topics');
        break;
      case '5':
        navigate('/broadcasts');
        break;
      case '6':
        navigate('/profile');
        break;
      case '7':
        navigate('/admin/tools');
        break;
      default:
        navigate('/home');
    }
  };

  const handleLogout = async () => {
    try {
      await auth.logout();
      if (setIsLoggedIn) {
        setIsLoggedIn(false);
      }
      navigate('/login');
    } catch (error) {
      console.error('登出失败:', error);
    }
  };

  if (!user) {
    return <div>加载中...</div>;
  }

  return (
    <Layout style={{ minHeight: '100vh', height: '100vh', overflow: 'hidden' }}>
      <Header
        className="site-layout-header"
        style={{
          padding: '0 18px',
          display: 'flex',
          justifyContent: 'space-between',
          position: 'fixed',
          top: 0,
          width: '100%',
          zIndex: 1000,
          // background: '#001529'
          background: 'linear-gradient(135deg, rgba(102, 126, 234) 0%, rgba(118, 75, 162) 100%)',
          border: 'none',
          color: 'white',
          fontWeight: 'bold'
        }}

      >
        <div className="logo" > 星域 PT</div>
        <Space style={{ marginRight: 32 }}>
          <Avatar icon={<UserOutlined />} />
          <span style={{ color: 'white' }}>{user.username}</span>
          <Button type="link" icon={<LogoutOutlined />} onClick={handleLogout} style={{ color: 'white' }}>
            登出
          </Button>
        </Space>
      </Header>
      <Layout style={{ marginTop: '64px', height: 'calc(100vh - 64px)' }}>
        <Sider
          width={200}
          style={{
            background: '#fff',
            position: 'fixed',
            left: 0,
            top: '64px',
            height: 'calc(100vh - 64px)',
            overflow: 'auto'
          }}
        >
          <Menu
            mode="inline"
            selectedKeys={[selectedMenuKey]}
            style={{ height: '100%', borderRight: 0 }}
            onClick={handleMenuClick}
          >
            <Menu.Item key="1" icon={<HomeOutlined />}>
              首页
            </Menu.Item>
            <Menu.Item key="2" icon={<DatabaseOutlined />}>
              资源中心
            </Menu.Item>
            <Menu.Item key="3" icon={<UploadOutlined />}>
              上传种子
            </Menu.Item>
            <Menu.Item key="4" icon={<TeamOutlined />}>
              话题社区
            </Menu.Item>
            <Menu.Item key="5" icon={<GlobalOutlined />}>
              全球广播
            </Menu.Item>
            <Menu.Item key="6" icon={<UserOutlined />}>
              个人中心
            </Menu.Item>
            {user && (user.role === 'admin' || user.role === 'moderator') && (
              <Menu.Item key="7" icon={<ToolOutlined />}>
                管理工具
              </Menu.Item>
            )}
          </Menu>
        </Sider>
        <Layout
          className="content-container"
          style={{
            marginLeft: '200px',
            height: 'calc(100vh - 64px)',
            overflow: 'auto'
          }}
        >
          <Content style={{ padding: '24px', minHeight: 'calc(100vh - 64px - 70px)' }}>
            {children}
          </Content>
          {/* <Footer style={{ textAlign: 'center' }}>
            星域 PT © 2023 Created with Ant Design
          </Footer> */}
        </Layout>
      </Layout>
    </Layout>
  );
};

export default CommonLayout; 